package com.lipaluma.test.db.rules;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.springframework.test.context.TestContextManager;

import com.lipaluma.test.db.DBTestContextManager;

/**
 * 
 * @author Mario
 */
public class SpringJunit4WithDBClassRule implements TestRule {

	private TestContextManager testContextManager;

	public SpringJunit4WithDBClassRule() {}
	
	@Override
	public Statement apply(Statement base, Description description) {
		if(testContextManager == null)
			this.testContextManager = new DBTestContextManager(description.getTestClass());

		return applyClassRule(base, description, description.getTestClass());
	}
	
	protected Statement applyClassRule(final Statement statement, Description description, Class<?> clazz) {

		return new Statement() {
			@Override
			public void evaluate() throws Throwable {
				testContextManager.beforeTestClass();
				try {
					statement.evaluate();
				} 
				finally {
					testContextManager.afterTestClass();
				}
			}
		};
	}

	public TestContextManager getTestContextManager() {
		return testContextManager;
	}
	
}
